package demo;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;

import util.StringDealer;
import dao.BaseDao;
import dao.PageDao;
import dao.QueryPageDao;
import dao.SegmentDao;
import dao.entity.SegmentEntity;

public class DemoCodeExtraction {
	//get a test connection, the user and pwd is hardcode.
	public static Connection conn = BaseDao.getTestConn();
	static int count = 0;
	public static void main(String args[]){
		
		//get the list of segment by query id, you can get the query id from query table in database(mysql), 
		//3440 is the id of "...BufferedReader..."  
		ArrayList<SegmentEntity> segList = QueryPageDao.getSegmentListByQueryID(conn, 3440, QueryPageDao.JAVA_FILE_FILTER);
		//get all pageid -> link
		HashMap<Integer, String> pageidMapLink = PageDao.getIDMapLink(conn);
		System.out.println(segList.size());
		for (int i=0; i<segList.size(); ++i){
			if (segList.get(i).getType() == SegmentEntity.CODE_SEGMENT ){
				String thisContent = segList.get(i).getContent();
				//trim the beginning empty line, and ending empty line. 
				thisContent = StringDealer.trimEmptyLine(thisContent);
				int thisLineNum = StringDealer.getLineNumber(thisContent);
				if (thisLineNum > 2 && thisLineNum < 100)
				{	
					printCodeAndSurroundingText(segList.get(i), pageidMapLink);			
				}
			}
		}
	}
	public static void printCodeAndSurroundingText(SegmentEntity codeSegment, HashMap<Integer, String> pageidMapLink){
		//get all segments from the page containing this code segment
		ArrayList<SegmentEntity> segments = SegmentDao.getSegmentListByPageID(conn, codeSegment.getPage_id());
		//get the index of this code segment in the page
		int i = 0;
		for(i = 0;i<segments.size();){
			if(segments.get(i).getIndex()==codeSegment.getIndex()){
				break;
			}
			i++;
		}
		
		System.err.println("++++++++++++++++USAGE EXAMPLE "+(++count)+" ++++++++++++++++++++++++");
		System.out.println("Pageid:" + codeSegment.getPage_id()
				+ ":" + pageidMapLink.get(codeSegment.getPage_id()));
		//print immediately preceding text segment
		System.out.println("[Preceding text:]");
		if((i-1)>=0){
			if(segments.get(i-1).getType() == SegmentEntity.NON_CODE_SEGMENT){
				System.out.println(segments.get(i-1).getContent());
			}
		}
		System.out.println("-------------------------------------------------");
		
		//print code segment		
		System.out.println("[Code snippet:]");
		System.out.println(codeSegment.getContent());					
		
		//print immediately following text segment
		System.out.println("-------------------------------------------------");
		System.out.println("[Following text:]");
		if((i+1)<segments.size()){
			if(segments.get(i+1).getType() == SegmentEntity.NON_CODE_SEGMENT){
				System.out.println(segments.get(i+1).getContent());
			}
		}
	}
}
